package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class AutoFillAspect {
    @Pointcut("@annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut() {
    }

    @Before("autoFillPointCut()")
    public void addCommonFields(JoinPoint joinPoint) {
        log.info("添加公共字段");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AutoFill autoFill = method.getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();
        LocalDateTime localDateTime = LocalDateTime.now();
        Long userId = BaseContext.getCurrentId();
        Object[] args = joinPoint.getArgs();
        if(args.length ==0 || args == null){
            return;
        }
        Object arg = args[0];
        if(operationType == OperationType.UPDATE) {
            log.info("更新操作");
            try {
                arg.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class).invoke(arg, localDateTime);
                arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class).invoke(arg, userId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if(operationType == OperationType.INSERT) {
            log.info("插入操作");
            try {
                arg.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class).invoke(arg, localDateTime);
                arg.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class).invoke(arg, localDateTime);
                arg.getClass().getDeclaredMethod("setUpdateUser", Long.class).invoke(arg, userId);
                arg.getClass().getDeclaredMethod("setCreateUser", Long.class).invoke(arg, userId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
